﻿using System;
using System.Net;
using Common.Base;
using Common.Base.Result;
using Common.Exceptions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Common.Filter
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<GlobalExceptionFilter> _logger;

        public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 异常处理方法
        /// </summary>
        /// <param name="context"></param>
        public void OnException(ExceptionContext context)
        {
            // 获取异常对象
            var exception = context.Exception;

            // 记录异常日志
            _logger.LogError(exception, $"发生未处理异常: {exception.Message}");

            // 构建统一的错误响应格式
            var result = new ResultData<bool>()
            {
                Code = 500,
                Msg = "服务器内部发生错误，请稍后再试"
            };

            if (exception is CustomException customException)
            {
                result.Msg = customException.Message;
                result.Code = customException.Code;
            }
            else if (exception is TokenException tokenException)
            {
                result.Msg = tokenException.Message;
                result.Code = tokenException.Code;
            }
            else if (exception is ArgumentException argumentException)
            {
                result.Msg = "参数错误";
            }

            // 设置异常已处理
            context.ExceptionHandled = true;
            // 设置处理结果
            context.Result = new ObjectResult(result);
        }
    }
}